/**
 * WorkOrderAction.java
 * Created at 2017-11-22
 * Created by zhanghailin
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.system.model.TmWoFile;
import com.broadtext.rms.system.model.TmWorkOrder;
import com.broadtext.rms.system.service.IWorkOrderService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>ClassName: WorkOrderAction</p>
 * <p>Description: TODO</p>
 * <p>Author: zhanghailin</p>
 * <p>Date: 2017-11-22</p>
 */
@Controller
@RequestMapping("/main/wo")
public class WorkOrderAction {
    
    @Autowired
    @Qualifier("workOrderService")
    private IWorkOrderService workOrderService;
    
    
    /**
     * 
     * <p>Description: 代码走一个差，来增加文档标注和方法描述</p>
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/getWorkOrder.mvc")
    @ResponseBody
    public Map<String,Object> getWorkOrder(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        PageBounds pageBounds = new PageBounds();
        //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //分页查询条数
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        //分页第几页
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            EntityPageBean<TmWorkOrder> pageBean = this.workOrderService.findEntityPageByQuery(map, pageBounds);
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return dataMap;
    }
    
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/getWorkOrderHistory.mvc")
    @ResponseBody
    public Map<String,Object> getWorkOrderHistory(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        PageBounds pageBounds = new PageBounds();
        //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //分页查询条数
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        //分页第几页
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            EntityPageBean<Object> pageBean = this.workOrderService.getWorkOrderHistory(map,pageBounds);
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return dataMap;
    }
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/getWorkOrderfile.mvc")
    @ResponseBody
    public Map<String,Object> getWorkOrderFile(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        PageBounds pageBounds = new PageBounds();
        //解析请求参数，将String字符串转为map
        Map<String,Object> map = new HashMap<String,Object>();
        String aoData = request.getParameter("aoData");
        JSONArray array = JSONArray.parseArray(aoData);
        if (array!=null) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && StringUtils.isNotBlank(obj.get("value")+"")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        //分页查询条数
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        //分页第几页
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            EntityPageBean<Object> pageBean = this.workOrderService.getWorkOrderFile(map,pageBounds);
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return dataMap;
    }
    
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param woId
     * @param woType
     * @return
     * @throws ServiceException
     */
    @RequestMapping(value = "/getWordOrderDetail.mvc")
    @ResponseBody
    public Map<String,Object> getWordOrderDetail(String woId, String woType) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        map = this.workOrderService.getWordOrderDetail(woId, woType);
        return map;
    }
    
    /**
     * 
     * <p>Description: TODO</p>
     * @param request
     * @param woId
     * @param woStatus
     * @param woType
     * @return
     */
    @RequestMapping(value = "/updateWoStatus.mvc")
    @ResponseBody
    public Map<String, Object> updateWoStatus(HttpServletRequest request ,String woId, String woStatus, String woType) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        String updateUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        try{
            this.workOrderService.updateWoStatus(woId, woStatus, woType, updateUser);
            dataMap.put("msg", "SUCCESS");
        } catch (ServiceException e) {
            dataMap.put("msg", "FAILURE");
            e.printStackTrace();
        }
        return dataMap;
    }
    
    @RequestMapping(value = "/upload2.mvc" , method = RequestMethod.POST )
    @ResponseBody
    public Map<String, Object> upload2(HttpServletRequest request,HttpServletResponse response,String woId)  {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();
            //获取工单id
            while(iter.hasNext()){  
                //记录上传过程起始时的时间，用来计算上传时间  
                int pre = (int) System.currentTimeMillis();  
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();  
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){  
                        System.out.println(myFileName);  
                        //重命名上传后的文件名
                        String extendName = myFileName.substring(myFileName.lastIndexOf(".")).toLowerCase();
                        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                        String fileName = "wo_"+format.format(new Date())+extendName; 
                        //定义上传路径  
                        String path = request.getSession().getServletContext().getRealPath("/")+"file\\"+fileName;  
                        File localFile =  new File(path); 
                        if(!localFile.getParentFile().exists()){
                            localFile.getParentFile().mkdirs();
                        }
                        try {
                            file.transferTo(localFile);
                            TmWoFile t = new TmWoFile();
                            t.setPkId(UUIDUtils.getUUID());
                            t.setFileName(fileName);
                            t.setWoId(woId);
                            t.setFileSize(file.getSize());
                            t.setFilePath(path);
                            System.out.println("===============文件大小:"+file.getSize());
                            t.setOriginalFileName(myFileName);
                            t.setCreateUser(String.valueOf(request.getSession().getAttribute("sys.userName")));
                            t.setCreateDate(new Date());
                            t.setDelFlag("0");
                            this.workOrderService.saveFile(t);
                            dataMap.put("msg", "SUCCESS");
                        } catch (Exception e) {
                            e.printStackTrace();
                            dataMap.put("msg", "FAIL");
                        }

                    }  
                }  
                //记录上传该文件后的时间  
                int finaltime = (int) System.currentTimeMillis();  
                System.out.println(finaltime - pre);  
            }  
        } 
        return dataMap;
    } 
    
    
    /**
     * 
     * <p>Description: 下载文件</p>
     * @param pkId
     * @param request
     * @param response
     */
    @RequestMapping(value = "/download.mvc")
    @ResponseBody
    public void download(String pkId, HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            //查询文件
            TmWoFile woFile = this.workOrderService.getWoFileById(pkId);
            //
            response.setContentType("application/x-download");
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(woFile.getOriginalFileName().getBytes("gb2312"), "ISO8859-1"));
            response.setCharacterEncoding("iso-8859-1");
            //设置header jquery 捕获成功标志
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            
            InputStream inputStream = new FileInputStream(new File(woFile.getFilePath()));
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
     * <p>
     * Description: 删除
     * </p>
     * 
     * @param request 请求
     * @param pkId id
     * @param response 返回对象
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/deleteFile.mvc")
    @ResponseBody
    public Object delete(HttpServletRequest request, String pkId, HttpServletResponse response) {
        //返回成功
        Map dataMap;
        dataMap = new HashMap();
        try {
            TmWoFile file = new TmWoFile();
            file.setPkId(pkId);
            file.setUpdateDate(new Date());
            file.setUpdateUser(String.valueOf(request.getSession().getAttribute("sys.userName")));
            file.setDelFlag("1");
            this.workOrderService.deleteFile(file);
            dataMap.put("msg", "SUCCESS");
        } catch (ServiceException e) {
            dataMap.put("msg", "FAILURE");
            e.printStackTrace();
        }
        return dataMap;
    }
    
    

}
